﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using OpenNOSClient;

namespace OpenNOSClientTest_for_Windows_Phone_7
{
    public class MainViewModel : INotifyPropertyChanged
    {
        public MainViewModel()
        {
            this.Items = new ObservableCollection<ItemViewModel>();
        }

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<ItemViewModel> Items { get; private set; }

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            this.Items.Add(new ItemViewModel { Title = "Getting Data", Description = "Please wait..." });

            string key = ""; // valid key here
            var client = OpenNOSRestClient.Create(key);

            var dispatcher = Deployment.Current.Dispatcher;
            var callback =
                    new OpenNOSRestClientAsync.OpenNOSRestCallback<IEnumerable<Article>>(articles =>
                    {
                        dispatcher.BeginInvoke(() => this.Items.Clear());
                        foreach (var article in articles)
                        {
                            var item = new ItemViewModel
                            {
                                Title = article.Title,
                                Description = article.Description
                            };

                            dispatcher.BeginInvoke(() => this.Items.Add(item));
                        }

                        this.IsDataLoaded = true;
                    }
            );

            client.GetLatestArticlesAsync(callback, OpenNOSCategory.Nieuws);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}